//获取数据

function gain() {
  $.ajax({
    type: 'GET',
    url: '/admin/links',
    success: function (res) {
      var tags = template('table-tpl', res)
      // console.log(tags);
      $('tbody').html(tags)
    }
  })
}

gain()

//添加
$('#add-link').on('click', function (e) {
  let lay = layer.open({
    type: 1,
    title: '添加友情链接',
    content: $('#add-form-tpl').html(),
    area: ['500px', '350px']
  })

  //添加链接中的上传图片
  $('body').on('click', '#urlIcon', function () {
    $('#linkFile').trigger('click')
  })

  //图片预览功能
  $('body').on('change', '#linkFile', function (e) {
    let objectURL = URL.createObjectURL(e.target.files[0])
    $('#preIcon').attr('src', objectURL)
  })

  //提交链接
  $('body').on('submit', '#add-form', function (e) {
    e.preventDefault()
    let fd = new FormData(this)
    $.ajax({
      type: 'POST',
      url: '/admin/links',
      data: fd,
      processData: false,
      contentType: false,
      success: function (res) {
        if (res.status === 0) {
          layer.close(lay)
          gain()
        }
      }
    })
  })
})




//编辑
$('body').on('click', '.edit', function (e) {
  let id = $(e.target).data('id')
  $.ajax({
    type: 'PUT',
    url: '/admin/links/' + id,
    success: function (res) {
      var index = layer.open({
        type: 1,
        title: '编辑友情链接',
        content: $('#edit-form-tpl').html(),
        area: ['500px', '350px']
      })
      // 设置预览图片效果
      $('#preIcon').attr('src', 'http://localhost:8888/uploads/' + res.data.linkicon)
      // 初始化表单数据
      delete res.data.linkicon
      form.val('editForm', res.data)

      $('body').on('click', '#urlIcon', function () {
        $('#linkFile').trigger('click')
      })
    }
  })
})



//删除
$('body').on('click', '.delete', function (e) {
  let id = $(e.target).data('id')
  layer.confirm('确定删除吗', function (index) {
    $.ajax({
      type: 'DELETE',
      url: '/admin/links/' + id,
      success: function (res) {
        if (res.status === 0) {
          layer.close(index)
          console.log('删除成功');
          gain()
        }
      }
    })
  })
})